<template>
    <div class="norm-form">
        <el-form ref="FormRef" :model="state.form" :rules="rules" label-width="auto" status-icon>
            <el-form-item label="报表" prop="tableId">
                <el-select v-model="state.form.tableId" placeholder="请选择报表">
                    <el-option :label="item.name" :value="item.id" v-for="item in state.tables" :key="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="采集对象" prop="collectObj">
                <el-select v-model="state.form.collectObj" placeholder="请选择采集对象">
                    <el-option :label="item.des" :value="item.code" v-for="item in state.categorys" :key="item.code" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="管理员层级" prop="level" v-if="state.form.collectObj == 'MANAGER'">
                <el-select v-model="state.form.level" placeholder="请选择管理员层级">
                    <el-option :label="item.des" :value="item.code" v-for="item in state.orgLevels" :key="item.code" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="类型" prop="type">
                <el-select v-model="state.form.type" placeholder="请选择类型" @change="typeChange">
                    <el-option v-for="item in state.types" :key="item.code" :label="item.des" :value="item.code" />
                </el-select>
            </el-form-item>
            <el-form-item label="固定时间点" prop="fixTime" v-if="state.form.type == 'FIX_DATE'">
                <el-date-picker v-model="state.form.fixTime" type="datetime" :disabled-date="disabledDateTime" value-format="YYYY-MM-DD HH:mm:ss" 
                    placeholder="请选择一个固定执行时间点" />
            </el-form-item>
            <el-form-item label="频率" prop="frequency" v-if="state.form.type == 'FIX_FREQUENCY'">
                <el-select v-model="state.form.frequency" placeholder="请选择频率">
                    <el-option v-for="item in state.frequencys" :key="item.code" :label="item.des" :value="item.code" />
                </el-select>
            </el-form-item>
            <el-form-item label="月" prop="month" v-if="state.form.frequency == 'YEAR'">
                <el-input-number v-model="state.form.month" :min="1" :max="12" />
            </el-form-item>
            <el-form-item label="日" prop="month"
                v-if="state.form.frequency == 'YEAR' || state.form.frequency == 'MONTH'">
                <el-input-number v-model="state.form.day" :min="1" :max="31" />
            </el-form-item>
            <el-form-item label="周" prop="week" v-if="state.form.frequency == 'WEEK'">
                <el-input-number v-model="state.form.week" :min="1" :max="7" />
            </el-form-item>
            <el-form-item label="cron表达式" prop="cron" v-if="state.form.frequency == 'INPUT_CRON'">
                <el-input v-model="state.form.cron" placeholder="请输入cron表达式" />
            </el-form-item>
            <el-form-item label="有效开始日期" v-if="state.form.type == 'FIX_FREQUENCY'">
                <el-date-picker v-model="state.form.start" type="date" value-format="YYYY-MM-DD" placeholder="开始日期"
                    :disabled-date="disabledDate" />
            </el-form-item>
            <el-form-item label="有效结束日期" v-if="state.form.type == 'FIX_FREQUENCY'">
                <el-date-picker v-model="state.form.end" type="date" value-format="YYYY-MM-DD" placeholder="结束日期"
                    :disabled-date="disabledDate" />
            </el-form-item>
            <el-form-item label="最近运行时间">
                <div>
                    <el-button type="primary" @click="generate">生成</el-button>
                    <div v-for="(item, index) in state.executeList" :key="index">{{ item }}</div>
                </div>
            </el-form-item>
            <el-form-item style="margin-top:40px">
                <el-button type="primary" @click="submit()">
                    保存
                </el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import { enums } from '@/api/common/common'
import { add, getNextExecuteTime } from '@/api/enact/plan'
import { noPlanList } from '@/api/enact/table'
import { useRouter } from 'vue-router'
import { Cron } from 'croner';


const router = useRouter()
const FormRef = ref(undefined)

const state = reactive({
    tables: [],
    categorys: [],
    orgLevels: [],
    types: [],
    frequencys: [],
    executeList: [],
    form: {
        tableId: undefined,
        type: undefined,
        fixTime: undefined,
        frequency: undefined,
        start: undefined,
        end: undefined,
        month: 1,
        day: 1,
        week: 1,
        cron: undefined,
        collectObj: undefined,
        // level: undefined,
    },
})

const validateCron = (rule, value, callback) => {
    if (!value) {
        callback(new Error('cron表达式不能为空'))
    } else {
        try {
            new Cron(value)
            callback()
        } catch (error) {
            callback('非法的Cron表达式')
        }
    }
}


const rules = reactive({
    tableId: [
        { required: true, message: '报表必选', trigger: 'change' },
    ],
    collectObj: [
        { required: true, message: '采集对象必选', trigger: 'change' },
    ],
    // level: [
    //     { required: true, message: '管理员层级必选', trigger: 'change' },
    // ],
    collectObj: [
        { required: true, message: '采集对象必选', trigger: 'change' },
    ],
    type: [
        { required: true, message: '类型必选', trigger: 'change' },
    ],
    fixTime: [
        { required: true, message: '固定时间必填', trigger: 'change' },
    ],
    frequency: [
        { required: true, message: '频率必选', trigger: 'change' },
    ],
    month: [
        { required: true, message: '月必填', trigger: 'change' },
    ],
    day: [
        { required: true, message: '日必填', trigger: 'change' },
    ],
    week: [
        { required: true, message: '日必填', trigger: 'change' },
    ],
    cron: [
        { required: true, message: 'cron表达式必填', trigger: 'blur' },
        { validator: validateCron, trigger: 'blur' }
    ]
})



const disabledDateTime = (time) => {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}
const disabledDate = (time) => {
    return time.getTime() < (new Date()).getTime()
}


const typeChange = (val) => {
    console.log("typeChange", val)
    if (val == 'FIX_DATE') {
        state.form.frequency = undefined
    } else if (val == 'FIX_FREQUENCY') {
        state.form.fixTime = undefined
    }
}

const generate = () => {
    state.executeList = []
    FormRef.value.validate((valid, fields) => {
        if (valid) {
            if (state.form.type == 'FIX_DATE') {
                state.executeList = [state.form.fixTime]
            } else {
                getNextExecuteTime(state.form).then(data => {
                    state.executeList = data
                })
            }
        }
    })
}

const submit = async () => {
    await FormRef.value.validate((valid, fields) => {
        if (valid) {
            add(state.form).then(data => {
                ElNotification({
                    title: '操作成功',
                    message: '计划新增成功',
                    type: 'success',
                })
                router.push('/plan-list')
            })
        }
    })
}



const cancel = () => {
    router.push('/plan-list')
}

const getTableList = () => {
    noPlanList().then(data => {
        state.tables = data
    })
}
const getTypeList = () => {
    enums('PlanType').then(data => {
        state.types = data
    })
}
const getFrequencysList = () => {
    enums('PlanFrequency').then(data => {
        state.frequencys = data
    })
}
const getUserTypeList = () => {
    enums('UserType').then(data => {
        state.userTypes = data
    })
}
const getCategoryList = () => {
    enums('CollectObjCategory').then(data => {
        state.categorys = data
    })
}
const getOrgTypeList = () => {
    enums('OrgLevel').then(data => {
        state.orgLevels = data
    })
}

onMounted(() => {
    getFrequencysList()
    // getUserTypeList()
    getCategoryList()
    // getOrgTypeList()
    getTypeList()
    getTableList()
})

</script>
<style scoped lang="scss"></style>
